//
//  GyroManager.swift
//  ShouChong
//
//  Created by yw on 2024/7/30.
//

import Foundation
import UIKit
import CoreMotion

public class GyroMannager {
    
    static var shared = GyroMannager()
    private let gyromanager = CMMotionManager()
    /// manager刷新时间间隔（采样频率设置为比屏幕刷新频率1/60稍小）
    public var timestamp:CGFloat = 0.016
    /// 用于记录引用 CMMotionManager 的数量
    private var useNumber:Int = 0
    
    private var isMoving:Bool = false
    public var count:Int = 0
    
    private init() {}
    

    
    func start(isPuase:Bool = false, speedBlock:@escaping(Double) -> Void, countBlock:@escaping (Int) -> Void) {
//        if self.gyromanager.isAccelerometerActive {
//        self.gyromanager.accelerometerUpdateInterval = 0.2
            self.gyromanager.startAccelerometerUpdates(to: OperationQueue.main) { data, error in
                if let gyroData = data {
                    let acceleration = gyroData.acceleration
                    let x = acceleration.x
                    let y = acceleration.y
                    let z = acceleration.z
                    let v = sqrt(x*x + y*y + z*z)
//                    print("v ---- \(v)")
//                    if isPuase {
//                        return 
//                        self.gyromanager.stopAccelerometerUpdates()
//                    } else {
//                        self.gyromanager.startAccelerometerUpdates()
//                    }
                    speedBlock(v)
                    if v > 1.8{
//                        print("加一")
//                        self.count += 1
//                        DPrint("start的值\(isPuase)")
                        if !self.isMoving{
                            self.count += 1
                            
                        }
                        self.isMoving = true
                    } else {
                        self.isMoving = false
                    }
                    countBlock(self.count)
                }
            }
//        }
    }
    
    func stop() {
        self.gyromanager.stopAccelerometerUpdates()
    }
    
    func resetCount() {
        stop()
        self.count = 0
    }
    
    
    
    func monitorDeviceMotion(index: Int) {
        useNumber += index
        if useNumber <= 0 {
            stopMotionUpdates()
        } else {
            startMotionUpdates()
        }
    }
    
    /// 开始陀螺仪
    private func startMotionUpdates() {
        if self.gyromanager.isGyroAvailable {
            if self.gyromanager.isGyroActive { return }
            self.gyromanager.gyroUpdateInterval = TimeInterval(self.timestamp)
            self.gyromanager.startGyroUpdates(to: OperationQueue.main) { [weak self] (data, nil) in
                if let gyroData = data {
                    print("陀螺仪---Updates---0")
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kCMMotionManagerUpdatesNotification"), object: self, userInfo: ["gyroData": gyroData])
                }
            }
        }
    }
    
    /// 停止陀螺仪
    private func stopMotionUpdates() {
        print("陀螺仪---stopMotionUpdates---", self.useNumber)
        if self.useNumber <= 0 {
            print("陀螺仪---stopMotionUpdates")
            self.gyromanager.stopGyroUpdates()
        }
    }
    
}

